//
//  AccessToken.swift
//  HMWeibo04
//
//  Created by apple on 15/3/3.
//  Copyright (c) 2015年 heima. All rights reserved.
//

import UIKit

///  AccessToken 类，access_token 是后续所有网络访问的重要依据
class AccessToken: NSObject, NSCoding {
    
    private static var _accessToken: AccessToken?
    /// 类属性，从沙盒懒加载 AccessToken
    class var accessToken: AccessToken? {
        if _accessToken == nil {
            _accessToken = loadAccessToken()
        }
        return _accessToken
    }
    
    ///  用于调用access_token，接口获取授权后的access token
    var access_token: String
    ///  token过期日期
    var expiresDate: NSDate
    ///  当前授权用户的UID
    var uid : Int
    
    /// 是否过期－用过期日期和当前时间进行比较
    var isExpired: Bool {
        return expiresDate.compare(NSDate()) == NSComparisonResult.OrderedAscending
    }
    
    ///  构造函数
    init(dict: NSDictionary) {
        access_token = dict["access_token"] as! String
        expiresDate = NSDate(timeIntervalSinceNow: dict["expires_in"] as! Double)
        uid = (dict["uid"] as! String).toInt() ?? 0
    }
    
    ///  将数据保存到沙盒
    func saveAccessToken() {
        NSKeyedArchiver.archiveRootObject(self, toFile: AccessToken.tokenPath())
    }

    ///  从沙盒读取 token 数据
    private class func loadAccessToken() -> AccessToken? {
        
        if let token = NSKeyedUnarchiver.unarchiveObjectWithFile(tokenPath()) as? AccessToken {
            if !token.isExpired {
                return token
            }
        }

        return nil
    }

    ///  返回保存在沙盒的路径
    private class func tokenPath() -> String {
        var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as! String
        path = path.stringByAppendingPathComponent("WBToken.plist")
        
        return path
    }
    
    // MARK: - 归档&接档
    func encodeWithCoder(encoder: NSCoder) {
        encoder.encodeObject(access_token, forKey: "access_token")
        encoder.encodeObject(expiresDate, forKey: "expiresDate")
        encoder.encodeInteger(uid, forKey: "uid")
    }

    required init(coder decoder: NSCoder) {
        access_token = decoder.decodeObjectForKey("access_token") as! String
        expiresDate = decoder.decodeObjectForKey("expiresDate") as! NSDate
        uid = decoder.decodeIntegerForKey("uid")
    }
}

extension AccessToken: DebugPrintable {
    
    override var debugDescription: String {
        let dict = self.dictionaryWithValuesForKeys(["access_token", "expiresDate", "uid"])
        return "\(dict)"
    }
}
